package com.jingzhi.count.netty;

import com.jingzhi.count.entity.Note;
import com.jingzhi.count.mapper.NoteMapper;
import com.jingzhi.count.utils.HexUtil;
import com.jingzhi.count.utils.TimeUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * 作者： 张恒同
 * 时间： 2018/3/26   17:51
 * 描述： 服务端接收数据
 */
@Component
@ChannelHandler.Sharable
public class HttpServerRevHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(HttpServerRevHandler.class);
    @Autowired
    private NoteMapper noteMapper;
    /**
     *  读取数据
     *
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        if (msg instanceof byte[]){
            String message = HexUtil.encodeHexStr((byte[]) msg);
            logger.info("服务端接收数据 - " + msg);
            logger.info("累加校验和 - " + HexUtil.makeChecksum(message));

            if ("00".equals(HexUtil.makeChecksum(message))) {
                if (!HexUtil.isDataType(message)) {
                    logger.info("心跳校验成功");
                } else if (HexUtil.isDataType(message)) {
                    logger.info("数据包校验成功");

                    Note note = new Note();
                    String mac = HexUtil.getMac(message);
                    if (mac != null) {
                        note.setSensorId(mac);
                        note.setTimeStamp(TimeUtils.getTimeStamp());
                        note.setNum(HexUtil.getSumByMsg(message));
                    }

                    noteMapper.insert(note);

                    logger.error("搜集酒瓶数 - " + caculateBottles());
                }

            }
            ctx.writeAndFlush(msg);
        }
    }

    /**
     *  计算酒瓶的总数
     *
     * */
    private int caculateBottles(){
        return noteMapper.countSum();
    }

    /**
     * 超时会触发该方法
     *
     * */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if (((IdleStateEvent) evt).state() == IdleState.WRITER_IDLE) {

            } else if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {

            } else if (((IdleStateEvent) evt).state() == IdleState.ALL_IDLE) {

            }
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }
}
